package org.codefinger.dao.impl.sql.ast;

import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.Expression;
import org.codefinger.dao.util.Lang;

public class AggregationExpression implements Expression {

	private Expression	exp;

	private String		preffix;

	public AggregationExpression(Expression exp, String aggName, boolean isDistinct) {
		super();
		this.exp = exp;
		if (isDistinct) {
			preffix = Lang.joinStr(aggName.length() + 1, aggName, "(");
		} else {
			preffix = Lang.joinStr(aggName.length() + 10, aggName, "(DISTINCT ");
		}
	}

	@Override
	public boolean matchVisit(SQLVisitor visitor) {
		int sqlSize = visitor.getSqlSize();
		visitor.appendSQL(preffix);
		if (exp.matchVisit(visitor)) {
			visitor.appendSQL(')');
			return true;
		}
		visitor.back(sqlSize);
		return false;
	}

	@Override
	public void visit(SQLVisitor visitor) {
		visitor.appendSQL(preffix);
		exp.visit(visitor);
		visitor.appendSQL(')');
	}

}
